package com.link.base.tencent.corpwx.accounttag.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.link.base.tencent.corpwx.accounttag.model.AccountTagGroup;
import com.link.base.tencent.corpwx.accounttag.model.AccountTagItem;
import com.link.base.wechat.basic.util.WxExceptionUtil;
import com.link.core.basic.service.BasicServiceException;
import com.link.core.util.HttpRequestUtil;
import com.link.core.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 企业微信 - 客户标签管理工具类
 * 
 * @author 欧阳振强
 * @date 2020/01/04
 */
public class AccountTagUtil {
    /**管理标签库 - 获取企业标签库接口*/
    private static final String GET_CORP_TAG_LIST_API = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_corp_tag_list?access_token=ACCESS_TOKEN";
    /**管理标签库 - 添加企业客户标签接口*/
    private static final String ADD_CORP_TAG_API = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/add_corp_tag?access_token=ACCESS_TOKEN";
    /**管理标签库 - 编辑企业客户标签接口*/
    private static final String EDIT_CORP_TAG_API = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/edit_corp_tag?access_token=ACCESS_TOKEN";
    /**管理标签库 - 删除企业客户标签接口*/
    private static final String DEL_CORP_TAG_API = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/del_corp_tag?access_token=ACCESS_TOKEN";
    /**管理客户标签 - 编辑客户企业标签接口*/
    private static final String MARK_ACCOUNT_TAG_API = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/mark_tag?access_token=ACCESS_TOKEN";

    /**
     * 管理标签库 - 获取企业标签库
     *
     * @author 欧阳振强
     * @date 2020/01/04
     * @param accessToken 接口凭证
     */
    public static JSONObject getCorpTagList(String accessToken) throws Exception {
        if (StringUtils.isBlank(accessToken)) {
            throw new BasicServiceException("accessToken不能为空！");
        }
        String url = GET_CORP_TAG_LIST_API.replace("ACCESS_TOKEN", accessToken);
        String resultStr = HttpRequestUtil.jsonPost(url, "");
        return WxExceptionUtil.parse(resultStr);
    }

    /**
     * 管理标签库 - 添加企业标签库 - 标签组
     *
     * @author 欧阳振强
     * @date 2020/01/04
     * @param accessToken 接口凭证
     * @param groupName 标签组名称
     * @param order 标签组排序
     * @param accountTagItemList 标签列表，取其中的标签名称和标签排序
     */
    public static JSONObject addCorpTagGroup(String accessToken, String groupName, String order,
                                             List<AccountTagItem> accountTagItemList) throws Exception {
        if (StringUtils.isBlank(accessToken)) {
            throw new BasicServiceException("accessToken不能为空！");
        }
        if (StringUtils.isBlank(groupName)) {
            throw new BasicServiceException("标签组名称不能为空！");
        }
        if (accountTagItemList == null || accountTagItemList.size() <= 0) {
            throw new BasicServiceException("标签组下的标签不能为空！");
        }
        String url = ADD_CORP_TAG_API.replace("ACCESS_TOKEN", accessToken);
        JSONObject obj = new JSONObject();
        obj.put("group_name", groupName);
        if (StringUtils.isNotBlank(order)) {
            obj.put("order", order);
        }
        obj.put("tag", getTagJSONArray(accountTagItemList));
        String param = obj.toJSONString();
        String resultStr = HttpRequestUtil.jsonPost(url, param);
        return WxExceptionUtil.parse(resultStr);
    }

    /**
     * 管理标签库 - 添加企业标签库 - 标签
     *
     * @author 欧阳振强
     * @date 2020/01/04
     * @param accessToken 接口凭证
     * @param groupId 标签组Id
     * @param accountTagItemList 标签列表，取其中的标签名称和标签排序
     */
    public static JSONObject addCorpTag(String accessToken, String groupId, List<AccountTagItem> accountTagItemList) throws Exception {
        if (StringUtils.isBlank(accessToken)) {
            throw new BasicServiceException("accessToken不能为空！");
        }
        if (StringUtils.isBlank(groupId)) {
            throw new BasicServiceException("标签组Id不能为空！");
        }
        if (accountTagItemList == null || accountTagItemList.size() <= 0) {
            throw new BasicServiceException("标签组下的标签不能为空！");
        }
        String url = ADD_CORP_TAG_API.replace("ACCESS_TOKEN", accessToken);
        JSONObject obj = new JSONObject();
        obj.put("group_id", groupId);
        obj.put("tag", getTagJSONArray(accountTagItemList));
        String param = obj.toJSONString();
        String resultStr = HttpRequestUtil.jsonPost(url, param);
        return WxExceptionUtil.parse(resultStr);
    }

    /**
     * 管理标签库 - 编辑企业标签库(标签组或标签)
     *
     * @author 欧阳振强
     * @date 2020/01/04
     * @param accessToken 接口凭证
     * @param id 标签组Id或标签Id
     * @param name 标签组名称或标签名称
     * @param order 标签组排序或标签排序
     */
    public static JSONObject editCorpTag(String accessToken, String id, String name, String order) throws Exception {
        if (StringUtils.isBlank(accessToken)) {
            throw new BasicServiceException("accessToken不能为空！");
        }
        if (StringUtils.isBlank(id)) {
            throw new BasicServiceException("标签组Id或标签Id不能为空！");
        }
        if (StringUtils.isBlank(name)) {
            throw new BasicServiceException("标签组名称或标签名称不能为空！");
        }
        String url = EDIT_CORP_TAG_API.replace("ACCESS_TOKEN", accessToken);
        JSONObject obj = new JSONObject();
        obj.put("id", id);
        obj.put("name", name);
        if (StringUtils.isBlank(order)) {
            obj.put("order", order);
        }
        String param = obj.toJSONString();
        String resultStr = HttpRequestUtil.jsonPost(url, param);
        return WxExceptionUtil.parse(resultStr);
    }

    /**
     * 管理标签库 - 删除企业标签库(标签组或标签)
     *
     * @author 欧阳振强
     * @date 2020/01/04
     * @param accessToken 接口凭证
     * @param groupIdList 标签组Id列表
     * @param tagIdList 标签Id列表
     */
    public static JSONObject delCorpTag(String accessToken, List<String> groupIdList, List<String> tagIdList) throws Exception {
        if (StringUtils.isBlank(accessToken)) {
            throw new BasicServiceException("accessToken不能为空！");
        }
        groupIdList = groupIdList == null ? new ArrayList<>() : groupIdList;
        tagIdList = tagIdList == null ? new ArrayList<>() : tagIdList;
        if (groupIdList.size() <= 0 && tagIdList.size() <= 0) {
            throw new BasicServiceException("标签组Id列表和标签Id列表不能同时为空！");
        }
        String url = DEL_CORP_TAG_API.replace("ACCESS_TOKEN", accessToken);
        JSONObject obj = new JSONObject();
        obj.put("tag_id", tagIdList);
        obj.put("group_id", groupIdList);
        String param = obj.toJSONString();
        String resultStr = HttpRequestUtil.jsonPost(url, param);
        return WxExceptionUtil.parse(resultStr);
    }

    /**
     * 编辑客户企业标签
     *
     * @author 欧阳振强
     * @date 2020/01/04
     * @param accessToken 接口凭证
     * @param userId 成员Id
     * @param externalContactId 客户Id
     * @param addTagList 需添加的标签Id列表
     * @param removeTagList 需删除的标签Id列表
     */
    public static JSONObject markAccountTag(String accessToken, String userId, String externalContactId,
                                            List<String> addTagList, List<String> removeTagList) throws Exception {
        if (StringUtils.isBlank(accessToken)) {
            throw new BasicServiceException("accessToken不能为空！");
        }
        if (StringUtils.isBlank(userId)) {
            throw new BasicServiceException("成员Id不能为空！");
        }
        if (StringUtils.isBlank(externalContactId)) {
            throw new BasicServiceException("客户Id不能为空！");
        }
        addTagList = addTagList == null ? new ArrayList<>() : addTagList;
        removeTagList = removeTagList == null ? new ArrayList<>() : removeTagList;
        if (addTagList.size() <= 0 && removeTagList.size() <= 0) {
            throw new BasicServiceException("添加标签Id和删除标签Id不能同时为空！");
        }
        String url = MARK_ACCOUNT_TAG_API.replace("ACCESS_TOKEN", accessToken);
        JSONObject obj = new JSONObject();
        obj.put("userid", userId);
        obj.put("external_userid", externalContactId);
        obj.put("add_tag", addTagList);
        obj.put("remove_tag", removeTagList);
        String param = obj.toJSONString();
        String resultStr = HttpRequestUtil.jsonPost(url, param);
        return WxExceptionUtil.parse(resultStr);
    }

    /**
     * 给定标签对象列表返回标签JSONArray
     * 
     * @author 欧阳振强
     * @date 2020/01/04
     */
    private static JSONArray getTagJSONArray(List<AccountTagItem> accountTagItemList) throws Exception {
        JSONArray tagList = new JSONArray();
        for (AccountTagItem item: accountTagItemList) {
            JSONObject tag = new JSONObject();
            tag.put("name", item.getTagName());
            if (StringUtils.isNotBlank(item.getTagOrder())) {
                tag.put("order", item.getTagOrder());
            }
            tagList.add(tag);
        }
        return tagList;
    }
    
    /**
     * 从给定标签对象中获取标签组对象
     * 
     * @author 欧阳振强
     * @date 2020/01/04
     * @param obj 标签组JSONObject
     */
    public static AccountTagGroup getTagGroupFromJSON(JSONObject obj) throws Exception {
        AccountTagGroup accountTagGroup = new AccountTagGroup();
        accountTagGroup.setTagGroupId(obj.getString("group_id"));
        accountTagGroup.setTagGroupName(obj.getString("group_name"));
        accountTagGroup.setCreateTime(obj.getString("create_time"));
        accountTagGroup.setTagGroupOrder(obj.getString("order"));
        accountTagGroup.setDeleted(obj.getString("deleted"));
        return accountTagGroup;
    }

    /**
     * 从给定标签对象中获取标签对象
     *
     * @author 欧阳振强
     * @date 2020/01/04
     * @param obj 标签JSONObject
     */
    public static AccountTagItem getTagItemFromJSON(JSONObject obj) throws Exception {
        AccountTagItem accountTagItem = new AccountTagItem();
        accountTagItem.setTagId(obj.getString("id"));
        accountTagItem.setTagName(obj.getString("name"));
        accountTagItem.setCreateTime(obj.getString("create_time"));
        accountTagItem.setTagOrder(obj.getString("order"));
        accountTagItem.setDeleted(obj.getString("deleted"));
        return accountTagItem;
    }

}
